<template>
  <div>
    <dialog-form
      ref="dialogForm"
      custom-class="mediate-dialog"
      width="600px"
      :title="title"
      :visible="visible"
      :form-attrs="{formData: modalFormData, renderFormItem, formButtons, labelWidth: '100px'}"
      @close="handleClose"
    />
    <dialog-map
      ref="dialogMap"
      :mark-type="markType"
      :map-visible.sync="mapVisible"
      @setCoordinate="setCoordinate"
    />
  </div>
</template>

<script>
import { propertyTypeMap } from '@/config/dict'
import { byKeyGetItem } from '@/utils'
import { fetchComponentPropertiesFindPage } from '@/api/basicinfo/parts/properties'
import { fetchDropDeptAllList, fetchDropAccountAllList, fetchDropDeviceList, fetchDropPartAllList, fetchDropPartTypeList } from '@/api/common/commonDropDown'
import { modalFormItem, formButtons } from './config'
import { DialogForm } from '@/components'
import DialogMap from './dialogMap'

export default {
  name: 'Update',
  components: { DialogForm, DialogMap },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '新增'
    },
    portId: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      renderFormItem: [], // 部件属性
      formButtons: formButtons(this.handleSubmit, this.handleClose),
      otherFormItem: [], // 其他 formItem

      cascaderConfig: [], // 负责人
      deviceList: [], // 设备下拉
      parentIdList: [], // 上级部件下拉
      dropPartTypeList: [], // 部门类型下拉

      parentIdShow: false, // 是否隐藏上级部件

      mapVisible: false,
      markType: 0,

      propertiesKey: [],
      mapData: {},
      modalFormData: {},

      rediusIsHide: true // 半径是否必填
    }
  },
  watch: {
    visible() {
      if (this.visible) {
        const { orgId } = this.modalFormData
        this.otherFormItem = []
        this.postDropDeviceList(orgId)
        this.postPartTypeList(orgId)
        this._createCascaderConfig()
      }
    }
  },
  methods: {
    setCoordinate() { // 设置地图标注的值
      const { coordinateSet, address } = this.$refs.dialogMap
      this.mapData = { coordinateSet: JSON.stringify(coordinateSet) }
      address && (this.mapData.address = address)
      this.$refs.dialogForm.$refs.modalForm.setFormData(this.mapData)
    },

    handleComponentTypeChange(e) { // 部件类别修改
      let isHide = true
      let type = 0
      let markType = 3
      this.rediusIsHide = true
      if (e === 2) {
        isHide = false
        type = 1
        markType = 2
        this.rediusIsHide = false
      } else if (e === 3) {
        isHide = false
        type = 4
        markType = 1
        this.rediusIsHide = false
      }
      this.parentIdShow = isHide
      this.markType = markType
      this.$refs.dialogForm.$refs.modalForm && this.$refs.dialogForm.$refs.modalForm.setFormData({ markType })
      !type && this._createRenderFormItem()
      type && this.postPartList(this.modalFormData.orgId, type)
    },

    handleComponentTypeIdChange(e) { // 部件类型修改
      if (!e) return false
      fetchComponentPropertiesFindPage({ componentId: this.portId, componentTypeId: e, page: 1, pagesize: 9999 }).then(res => {
        const list = res.records
        list && list.length && this._createOtherFormItem(list)
      })
    },

    handleMarkTypeChange(e) { // 标注类型修改
      this.modalFormData.coordinateSet = null
      this.markType = e
    },

    handleSubmit(values) {
      if (!this._formatFormData(values)) return false
      values.deviceIdStr = values.deviceIdList ? values.deviceIdList.join(',') : ''
      values.headerAccountId = values.headerAccountIdList[1]
      this.$emit('handleModalSubmit', values)
    },

    handleClose() {
      this.$emit('update:visible', false)
    },

    handleAnnotation() { // 点击标注
      this.markType = this.markType || this.modalFormData.markType
      if (!this.markType) {
        this.$message.warning('请选择标注方式!')
        return false
      }
      const temp = JSON.parse(this.modalFormData.coordinateSet || this.mapData.coordinateSet || '[]')
      const coordinateSet = this.markType === 1 ? temp[0] : temp
      this.$refs.dialogMap.setPosition(coordinateSet, this.markType, this.modalFormData.address)
      this.mapVisible = true
    },

    _createCascaderConfig() { // 创建 formitem
      this.cascaderConfig = {
        lazy: true,
        lazyLoad: (node, resolve) => {
          const { level, value } = node
          if (level === 0) {
            this.postDeptAllList(this.modalFormData.orgId).then(res => {
              resolve(res)
            })
          } else {
            this.postAccountAllList(value).then(res => {
              resolve(res)
            })
          }
        }
      }
      this._createRenderFormItem()
    },

    _createRenderFormItem(parentIdList, parentIdShow, otherFormItem) { // 创建renderFormItem
      parentIdList = parentIdList || this.parentIdList
      parentIdShow = parentIdShow || this.parentIdShow
      otherFormItem = otherFormItem || this.otherFormItem
      this.renderFormItem = modalFormItem(
        this.handleComponentTypeChange,
        this.handleComponentTypeIdChange,
        this.handleMarkTypeChange,
        this.handleAnnotation,
        this.cascaderConfig,
        this.deviceList,
        this.dropPartTypeList,
        this.rediusIsHide,
        parentIdList,
        parentIdShow,
        otherFormItem
      )
    },

    _createOtherFormItem(list) { // 创建otherFormItem
      this.propertiesKey = []
      this.otherFormItem = list.map(item => {
        const propertyObj = byKeyGetItem(propertyTypeMap, item.propertyType)
        const { value } = item
        const newValue = !propertyObj.multiple
          ? value
          : value ? value.split(',') : value
        this.$refs.dialogForm.$refs.modalForm.setFormData({
          ['componentProperties__' + item.id]: newValue
        })
        this.propertiesKey.push('componentProperties__' + item.id)
        const optionList = item.options ? item.options.split('|') : []
        const options = []
        optionList.length && optionList.map(item => {
          options.push({ key: item, value: item })
        })
        const style = { width: '95.8%' }
        // const isSpecial = propertyObj.multiple || propertyObj.type === 'textarea'
        return {
          type: propertyObj.type,
          label: item.propertyName,
          key: 'componentProperties__' + item.id,
          required: item.required,
          otherAttrs: {
            labelWidth: '120px'
          },
          slotAttrs: {
            placeholder: item.promptText,
            multiple: propertyObj.multiple,
            style: style,
            options
          },
          col: 24
        }
      })
      this._createRenderFormItem()
    },

    _formatFormData(formData) { // 数据处理
      if (!formData.headerAccountIdList[1]) {
        this.$message.warning('请选择负责人!')
        return false
      }
      if (!formData.coordinateSet || formData.coordinateSet === 'null') {
        this.$message.warning('请设置标注!')
        return false
      }
      formData.componentDataList = this._formatPartData(formData)
      formData.headerAccountId = formData.headerAccountIdList[1]
      return true
    },

    _formatPartData(formData) { // 格式化 componentDataList
      const partData = []
      for (const key in formData) {
        if (key.includes('componentProperties__')) {
          const value = formData[key]
          if (this.propertiesKey.includes(key)) {
            partData.push({
              componentId: this.modalFormData.id || 0,
              componentProperties: +key.split('__')[1],
              value: Array.isArray(value) ? value.join(',') : value
            })
          }
        }
      }
      return partData
    },

    postDropDeviceList(orgId) { // 获取设备下拉
      fetchDropDeviceList({ orgId, bindType: 2 }).then(res => {
        this.deviceList = res.map(item => ({ key: item.id, value: item.name }))
        this._createRenderFormItem()
      })
    },

    postDeptAllList(orgId) { // 部门下拉
      return fetchDropDeptAllList({ orgId }).then(res => {
        return res.map(e => ({ label: e.name, value: e.id }))
      })
    },
    postAccountAllList(deptId) { // 人员下拉
      return fetchDropAccountAllList({ deptId }).then(res => {
        return res.map(e => ({ label: e.name, value: e.id, leaf: true }))
      })
    },

    postPartList(orgId, type = 0) { // 上级部件
      return fetchDropPartAllList({ orgId, type }).then(res => {
        this.parentIdList = res.map(e => ({ key: e.id, value: e.name }))
        this._createRenderFormItem()
      })
    },

    postPartTypeList(orgId) { // 部件类型下拉
      fetchDropPartTypeList({ orgId }).then(res => {
        this.dropPartTypeList = res.map(item => ({ key: item.id, value: item.typeName }))
        this._createRenderFormItem()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.part-update {
  .clear {
    clear: both;
  }

  .btns {
    margin-top: 20px;
    float: right;
  }

  .part-title {
    font-size: 16px;
    color: #272727;
    margin: 0 0  20px 10px;
    font-weight: bold;
  }

  .hide {
    display: none;
  }
}
</style>
